package com.maxdu.labs.stt.activities;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.example.stt.R;
import com.facebook.widget.ProfilePictureView;
import com.maxdu.labs.stt.constants.Constants;
import com.maxdu.labs.stt.models.TPlan;
import com.maxdu.labs.stt.models.User;
import com.maxdu.labs.stt.models.db.FriendRequestDBHelper;
import com.maxdu.labs.stt.models.db.UserVSTPlanDBHelper;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;

public class SeeTPlanDetailActivity extends Activity {

	private TPlan tplan;
	private TextView trainingNameTV;
	private TextView footer1TV;
	private TextView footer2TV;
	private Button inviteBtn;
	private ListView peopleLV;
	
	private ProgressBar progressBar;
	
	private List<String> people;
	private List<User> allFriends;
	
	private PeopleAdapter adapter;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_see_tplan_detail);
		
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();

        if(bundle!=null)
        {
            tplan =(TPlan) bundle.get("tplan");
            if(tplan != null){
            	
            	progressBar = (ProgressBar) findViewById(R.id.progressBar1);
            	trainingNameTV = (TextView) findViewById(R.id.training_name);
            	trainingNameTV.setText(tplan.getName());
            	peopleLV = (ListView) findViewById(R.id.list_people);
            	inviteBtn = (Button)findViewById(R.id.btn_invite);
            	
            	inviteBtn.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						Intent intent = new Intent(SeeTPlanDetailActivity.this,InviteFriendsToTPlanActivity.class);
						if (people != null && people.size()>0){
							intent.putExtra("people", getByteArray(people));
							intent.putExtra("trainingId", tplan.getId());
						}
						startActivity(intent);
					}
				});
            	
            	boolean justCreated = false;
            	if(bundle.get("justCreated") != null){
            		justCreated= (Boolean) bundle.get("justCreated");
            	}
            	people = new ArrayList<String>();
            	if (justCreated){
            		//we just created this tplan. So there is no user linked to it except the currentUser
            		String currentUser;
            		if (bundle.get("currentUser") != null){
            			currentUser = (String)bundle.get("currentUser");
            			people.add(currentUser);
            		}
            	}else{
            		
            		allFriends = new ArrayList<User>();
            		
	            	GetUsersAlreadyInTraining task = new GetUsersAlreadyInTraining();
	            	task.execute(tplan.getId());
            	}
                adapter = new PeopleAdapter(getApplicationContext(), R.layout.row_people, people);
                peopleLV.setAdapter(adapter);
            	
            }else{
            	TextView somethingWentWrongTV = (TextView) findViewById(R.id.something_went_wrong);
            	somethingWentWrongTV.setVisibility(View.GONE);
            	Log.e(Constants.LOG_TAG, "Error: SeeTPlanActivity: we couldn't retrieve from intent the TPlan Object");
            }
        }else{
        	TextView somethingWentWrongTV = (TextView) findViewById(R.id.something_went_wrong);
        	somethingWentWrongTV.setVisibility(View.GONE);
        	Log.e(Constants.LOG_TAG, "Error: SeeTPlanActivity: we couldn't retrieve from intent the TPlan Object");
        }
	}

	private byte[] getByteArray(List<String> users) {

	    try {
	        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
	        new ObjectOutputStream(outputStream).writeObject(users);
	        return outputStream.toByteArray();
	    } catch (IOException e) {
	        Log.e(Constants.LOG_TAG, "Unable to serialize users.", e); 
	    }   
	    return null;
	}   
	
	private class GetUsersAlreadyInTraining extends AsyncTask<String, Void, List<String>> {

	    @Override
		protected void onPreExecute() {
			super.onPreExecute();
			progressBar.setVisibility(View.VISIBLE);
		}
		
		@Override
	    protected List<String> doInBackground(String... params) {

	    	if (params != null){
	    		
	    		ParseQuery<ParseObject> query = ParseQuery.getQuery(UserVSTPlanDBHelper.PARSE_DB_TABLENAME_USERVSTPLAN);
	    		query.whereEqualTo(UserVSTPlanDBHelper.PARSE_DB_FIELD_TPLANID, params[0]);
	    		
	    		Log.d(Constants.LOG_TAG, "GetUsersAlreadyInTraining:: About to try to get the users already in the tplan:: " + params[0]);
	    		
	    		query.findInBackground(new FindCallback<ParseObject>() {
	    		    public void done(List<ParseObject> list, ParseException e) {
	    		        if (e == null) {
	    		        	if (list != null && list.size()> 0){
	    		        		for (ParseObject userVSTrainingParseObject : list){
	    		        			String user = userVSTrainingParseObject.getString(FriendRequestDBHelper.PARSE_DB_FIELD_SENDERID);
	    		        			people.add(user);
	    		        		}
	    		        		
	    		        		Log.d(Constants.LOG_TAG, "GetUsersAlreadyInTraining::we successfully retrieved [" + people.size()+"] users already in the Traiing [" + list.get(0).getString(UserVSTPlanDBHelper.PARSE_DB_FIELD_TPLANID));
	    		        		adapter.notifyDataSetChanged();
	    		        		progressBar.setVisibility(View.GONE);
	    		        		
	    		        		inviteBtn.setOnClickListener(new OnClickListener() {
									@Override
									public void onClick(View arg0) {
										Intent intent = new Intent(SeeTPlanDetailActivity.this,InviteFriendsToTPlanActivity.class);
										if (people != null && people.size()>0){
											intent.putExtra("people", getByteArray(people));
										}
										startActivity(intent);
									}
								});
	    		        		
	    		        		
	    		        	}else if(list == null){
	    		        		Log.d(Constants.LOG_TAG, "we couldn't retrieve the pending UserVSTPlan for the current TPlan: users list is NULL");
	    		        	}else{
	    		        		Log.d(Constants.LOG_TAG, "we couldn't retrieve the pending UserVSTPlan for the current TPlan: users list is EMPTY");
	    		        		progressBar.setVisibility(View.GONE);
	    		        		//noPendingRequestTView.setVisibility(View.VISIBLE);
	    		        		
	    		        	}
	    		        } else {
	    		            Log.d(Constants.LOG_TAG, "Error: " + e.getMessage());
	    		        }
	    		    }
	    		});
	    		
	    		return people;
	    	}
	    	return null;
	    	
	    }
	}
	
	private class PeopleAdapter extends ArrayAdapter<String>{

		List<String> _people;
		
		public PeopleAdapter(Context context, int resource,
				List<String> objects) {
			super(context, resource, objects);
			
			_people = objects;
		}
		
		@Override
	    public View getView(final int position, View convertView, ViewGroup parent) {
	        View view = convertView;
	        if (view == null) {
	        	LayoutInflater inflater = (LayoutInflater)getContext().getSystemService
	        		      (Context.LAYOUT_INFLATER_SERVICE);
	            view = inflater.inflate(R.layout.row_people, parent,false);
	        }

	        String userId = _people.get(position);
	        
            TextView nameTextV = (TextView) view.findViewById(R.id.friendrequest_name);
            ProfilePictureView profilePictureView = (ProfilePictureView)view.findViewById(R.id.friendrequest_picture);
            profilePictureView.setProfileId(userId);
            
            nameTextV.setText("fake name");
	        
	        return view;
	    }
	}
}
